import { saveAs } from "file-saver";
import axios from "axios";
import { ElMessage } from "element-plus";

/**
 * 导出Markdown
 * @param name 文档名称
 * @param content 文档内容
 */
export const exporMarkdown = (name: string, content: string) => {
  saveAs(new Blob([content], { type: "text/plain;charset=utf-8" }), `${name}.md`);
};

/**
 * 导出html格式的OpenAPI
 * @param name 文档名称
 * @param content 文档内容
 * @returns
 */
export const exportOpenApi = (name: string, content: string) => {
  return new Promise((resolve, reject) => {
    Promise.all([axios.get("/static/stoplight-elements/web-components.min.js"), axios.get("/static/stoplight-elements/styles.min.css")])
      .then((arr) => {
        let html = `<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="icon" href="" />
    <title>${name}</title>
    <style>
      ${arr[1].data}
      body {
        position: fixed;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
      }
      #mosaic-provider-react-aria-0-1
        > div
        > div
        > div
        > div.sl-flex
        > div.sl-flex.sl-overflow-y-auto.sl-flex-col.sl-sticky.sl-inset-y-0.sl-pt-8.sl-bg-canvas-100.sl-border-r
        > a {
        display: none;
      }
      #mosaic-provider-react-aria-0-1
        > div
        > div
        > div
        > div.sl-flex
        > div.sl-flex.sl-overflow-y-auto.sl-flex-col.sl-sticky.sl-inset-y-0.sl-pt-8.sl-bg-canvas-100.sl-border-r {
        padding-top: 10px;
      }
      #mosaic-provider-react-aria-0-1 > div > div > div > div.sl-overflow-y-auto.sl-flex-1.sl-w-full.sl-px-24.sl-bg-canvas {
        min-width: 800px;
      }
      #mosaic-provider-react-aria-0-1 > div > div > div {
        overflow-x: auto;
      }
    </style>
  </head>
  <body>
    <script>
      ${arr[0].data}
      var child = document.createElement("elements-api");
      child.setAttribute("router", "hash");
      child.setAttribute("hideExport", true);
      child.setAttribute("hideSchemas", true);
      child.setAttribute("apiDescriptionDocument", \`${content}\`);
      document.body.appendChild(child);
    <\/script>
  </body>
</html>`;
        saveAs(new Blob([html], { type: "text/plain;charset=utf-8" }), `${name}.html`);
        resolve(true);
      })
      .catch((err) => {
        ElMessage.warning("下载失败");
        reject(err);
      });
  });
};
